package group.itk.vuelogintestbackend.login

import com.google.gson.Gson
import com.google.gson.JsonObject
import group.itk.vuelogintestbackend.login.entity.User
import org.apache.shiro.SecurityUtils
import org.apache.shiro.authc.UsernamePasswordToken
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.*
import java.util.*
import javax.servlet.http.HttpServletRequest

@RestController
class LoginController {

  @Autowired
  private lateinit var loginService: LoginService

  @PostMapping("/login")
  @CrossOrigin
  fun login(@RequestBody user: User, request: HttpServletRequest): String {
    //从前端获取数据，并将数据包装
    val currentUser = SecurityUtils.getSubject()
    val token = request.getHeader("token")
    println("$user--$token")
    return if (!StringUtils.hasText(token)) {
      val loginedJson = loginService.login(UsernamePasswordToken(user.username, user.password))
      if (loginedJson["code"].asNumber == 200) {
        loginedJson.addProperty("token", UUID.randomUUID().toString())
        loginedJson.add("user", JsonObject().apply { addProperty("username", "Administrator") })
      }
      Gson().toJson(loginedJson)
    } else {
      Gson().toJson(JsonObject().apply {
        addProperty("code", 200)
        add("user", JsonObject().apply { addProperty("username", "Administrator") })
        addProperty("msg", "您已经登录")
        addProperty("token", token)
      })
    }
  }

  @PostMapping("/logout")
  @CrossOrigin
  fun logout(request: HttpServletRequest): String {
    var json = JsonObject()

    if (StringUtils.hasText(request.getHeader("token"))) {
      val logout = loginService.logout()
      json = logout
      return Gson().toJson(json)
    }
    json.addProperty("code", 400)
    json.addProperty("msg", "logout failed")
    return Gson().toJson(json)
  }
}
